<script setup>
import { onBeforeMount, ref } from "vue";

import { ToastFun } from "@/hook/toast";

import {
  twoRebate,
  zoneLeader,
  selectZone,
  firstRebate,
  createZones,
  selectTwoZone,
  addUserByZone,
  selectTwoZones,
  invitationCode,
  selectUserZoneByUid,
} from "@/server/api/activity";

import { useUseStore } from "@/stores/user";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
let pageShow = ref(false);
let show = ref(false); // 控制弹出层显示隐藏
let userId = useUseStore().userId; // 用户id
let code = ref(""); // 绑定用户输入的邀请码，用于添加到某个团
let secZoneArr = ref([]); // 用于渲染二级团的数据

/**
 * 添加用户专区信息
 */
const addUserByZoneFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  try {
    await addUserByZone({ userId });
    // 无论是否已有用户信息，都请求一次信息接口
    selectUserZoneByUidFun();
  } catch {
    ToastFun("");
  }
};

/**
 * 根据Id查找用户专区信息
 */
const selectUserZoneByUidFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await selectUserZoneByUid(userId);
    if (data.code == 200) {
      ToastFun("success");
      useUseStore().activityInfo = data.data;

      pageShow.value = true;

      !data.data.newZoneId || (selectZoneFun() && selectTwoZonesFun());
    } else {
      ToastFun("");
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 将用户升级为团长
 */
const zoneLeaderFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await zoneLeader({ userId });

    if (data.code == 200) {
      ToastFun("success");
      useUseStore().activityInfo.isGroupLeader = 1;
    } else {
      ToastFun("show", { msg: t("point.tip1") });
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 根据用户id创建一级、二级团
 */
const createZonesFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await createZones({ userId });

    if (data.code == 200) {
      useUseStore().activityInfo.newZoneId = data.data; // 将一级团id保存到信息中

      selectZoneFun(); // 查询一级团信息
      selectTwoZonesFun(); // 查询二集团信息
    } else {
      ToastFun("");
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 根据用户名和一级团id查询当前一级团信息
 */
const selectZoneFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  let obj = {
    userId,
    firstZoneId: useUseStore().activityInfo.newZoneId,
  };

  try {
    let { data } = await selectZone(obj);

    if (data.code == 200) {
      // 图片路径拼接
      if (data.data.zoneUserInfoVOList && data.data.zoneUserInfoVOList.length) {
        data.data.zoneUserInfoVOList.forEach((item) => {
          let imgList = item.userImage.split(".");
          item.userImage =
            useUseStore().ing + imgList[0] + "_80_80." + imgList[1];
        });
      }

      useUseStore().activityInfo.firstZoneInfo = data.data; // 将一级团信息保存到库中
      useUseStore().rebateQualification = data.data.rebateQualification;
      useUseStore().levelRebate = data.data.levelRebate;

      ToastFun("success");
    } else {
      ToastFun("");
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 查询用户名和一级团id查询二级团信息
 */
const selectTwoZonesFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  let obj = {
    userId,
    firstZoneId: useUseStore().activityInfo.newZoneId,
  };

  try {
    let { data } = await selectTwoZones(obj);

    if (data.code == 200) {
      // 图片拼接
      data.data.forEach((item) => {
        if (item.zoneUserInfoVOList != null) {
          item.zoneUserInfoVOList.forEach((_) => {
            let imgList = _.userImage.split(".");
            _.userImage =
              useUseStore().ing + imgList[0] + "_80_80." + imgList[1];
          });
        }
      });

      useUseStore().activityInfo.SecZoneInfo = data.data; // 将二级团信息保存到库中

      ToastFun("success");
    } else {
      ToastFun("");
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 通过邀请码入团
 */
const invitationCodeFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await invitationCode({ userId, invitationCode: code.value });
    data.code == 200 ? ToastFun("success") : ToastFun("");
  } catch {
    ToastFun("");
  }
};

/**
 * 显示二级团列表方法
 * @param {object} item 对象
 * @param {string} item.userId 传入要显示的团对应的userId
 */
const secZoneShowFun = (item) => {
  // 找到对应userId的团信息
  let index = useUseStore().activityInfo.SecZoneInfo.findIndex(
    (_) => _.userId == item.userId
  );

  if (index != -1) {
    secZoneArr.value =
      useUseStore().activityInfo.SecZoneInfo[index].zoneUserInfoVOList;

    show.value = true;
  } else {
    ToastFun("show", { msg: t("point.tip2") });
  }
};

/**
 * 一级团返佣
 */
const firstRebateFun = async () => {
  // 请求前的校验
  if (useUseStore().activityInfo.firstZoneInfo.invalid == 1) {
    ToastFun("show", { msg: t("point.tip3") });
    return;
  } else if (
    useUseStore().activityInfo.firstZoneInfo.rebateQualification == 0
  ) {
    ToastFun("show", { msg: t("point.tip4") });
    return;
  }

  ToastFun("Loading", { duration: 1000 });

  let obj = {
    userId,
    zoneId: useUseStore().activityInfo.newZoneId,
  };

  try {
    let { data } = await firstRebate(obj);

    if (data.code == 200) {
      ToastFun("success");
      useUseStore().activityInfo.firstZoneInfo.levelRebate = 1;
      useUseStore().activityInfo.firstZoneInfo.rebateQualification = 1;
    } else {
      ToastFun("show", { msg: t("point.tip4") });
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 二级团返佣
 */
const twoRebateFun = async () => {
  // 请求体
  let obj = {
    userId,
    zoneId: useUseStore().activityInfo.newTwoZoneId,
  };

  // 请求前的校验
  let { data } = await selectTwoZoneFun(obj);

  if (data.invalid == 1) {
    ToastFun("show", { msg: t("point.tip3") });
    return;
  } else if (data.rebateQualification == 0) {
    ToastFun("show", { msg: t("point.tip4") });
    return;
  }

  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await twoRebate(obj);

    if (data.code == 200) {
      ToastFun("success");
      console.log(data.data);
    } else {
      ToastFun("show", { msg: t("point.tip4") });
    }
  } catch {
    ToastFun("");
  }
};

/**
 * 二级团是否可返利及是否失效
 */
const selectTwoZoneFun = async (obj) => {
  ToastFun("Loading", { duration: 1000 });

  try {
    let { data } = await selectTwoZone(obj);

    console.log(data);

    return data;
  } catch {
    ToastFun("");
  }
};

onBeforeMount(() => {
  // 判断使用有用户活动的数据，没有则请求接口将用户添加到活动表中，有则显示页面
  useUseStore().activityInfo == null
    ? addUserByZoneFun()
    : (pageShow.value = true);

  !useUseStore().activityInfo ||
    !useUseStore().activityInfo.newZoneId ||
    (selectZoneFun() && selectTwoZonesFun()); // 当拥有专区信息且拥有团Id时，获取当前一二级团信息
});
</script>

<template>
  <div class="activityPage" v-if="pageShow">
    <div class="top">
      <van-icon name="arrow-left" class="backBtn" @click="$router.back" />
      <div class="title">活动标题</div>
    </div>

    <div class="user">
      <div class="info">
        <div class="img">
          <img v-lazy="useUseStore().userInfo.userImage" alt="" />
        </div>
        <div class="name">{{ useUseStore().userInfo.userName }}</div>
      </div>

      <!-- 升级团长按钮 -->
      <div class="btn" @click="zoneLeaderFun" v-if="useUseStore().activityInfo.isGroupLeader == 0">
        upgrade
      </div>

      <!-- 开团按钮 -->
      <div class="btn" @click="createZonesFun" v-if="
        !useUseStore().activityInfo.newZoneId &&
        useUseStore().activityInfo.isGroupLeader == 1
      ">
        开团
      </div>

      <!-- 一级团返佣按钮 -->
      <div class="btn" @click="firstRebateFun" v-if="
        useUseStore().activityInfo.isGroupLeader == 1 &&
        useUseStore().activityInfo.newZoneId &&
        useUseStore().levelRebate == 0 &&
        useUseStore().rebateQualification == 1
      ">
        一级返佣
      </div>

      <!-- 二级团返佣按钮 -->
      <div class="btn" @click="twoRebateFun" v-if="
        useUseStore().activityInfo.isGroupLeader == 1 &&
        useUseStore().activityInfo.newZoneId &&
        useUseStore().levelRebate == 1 &&
        useUseStore().rebateQualification == 1
      ">
        二级返佣
      </div>
    </div>

    <div class="second" v-if="useUseStore().activityInfo.firstZoneInfo">
      <div :key="i" class="item" @click="secZoneShowFun(item)" v-for="(item, i) in useUseStore().activityInfo.firstZoneInfo
        .zoneUserInfoVOList">
        <img v-lazy="item.userImage" alt="" class="img" />
        <div class="name cut-txt">{{ item.userName }}</div>
        <div class="price cut-txt">{{ item.zoneConsumptionSum }}%</div>
      </div>

      <div class="item" v-for="(item, i) in 10 -
        useUseStore().activityInfo.firstZoneInfo.zoneUserInfoVOList.length" :key="i">
        <div class="add"></div>
      </div>
    </div>

    <van-popup v-model:show="show" class="third" position="center">
      <div :key="i" class="item" @click="secZoneShowFun(item)" v-for="(item, i) in secZoneArr">
        <img v-lazy="item.userImage" alt="" class="img" />
        <div class="name cut-txt">{{ item.userName }}</div>
        <div class="price cut-txt">{{ item.zoneConsumptionSum }}%</div>
      </div>

      <div class="item" v-for="(item, i) in 10 - secZoneArr.length" :key="i">
        <div class="add"></div>
      </div>
    </van-popup>

    <div class="invite">
      <div class="input">
        <input type="text" v-model="code" />
        <div class="btn" @click="invitationCodeFun">join</div>
      </div>

      <span v-if="useUseStore().activityInfo.firstZoneInfo">
        your code: {{ useUseStore().activityInfo.firstZoneInfo.invitationCode }}
      </span>
    </div>

    <p class="tips">
      <span>Rules: </span> <br />
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officia dolorem
      vitae rem totam ipsa debitis doloremque unde, dolore ab voluptate,
      provident recusandae ullam. Officiis eius dicta aliquid sed rerum ipsum
      repudiandae suscipit voluptatem sit quos maiores, assumenda tenetur
      impedit inventore nihil, est natus. Nihil distinctio quidem sapiente
      asperiores laborum sunt praesentium aut perferendis est repudiandae,
      exercitationem beatae assumenda architecto possimus id ducimus quas odio
      enim sit eius iusto libero vitae eaque harum! Amet cupiditate dolores
      facilis.
    </p>
  </div>
</template>

<style lang="scss" scoped>
@mixin item {
  width: 20%;
  height: 70rem;
  padding: 5rem 0;

  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  font-size: 12rem;
  font-weight: 500;

  >.img {
    width: 30rem;
    height: 30rem;
    border-radius: 50%;
    overflow: hidden;
  }

  >.add {
    position: relative;
    width: 40rem;
    height: 40rem;
    border: 1rem solid #bebebe;
    border-radius: 50%;

    margin-top: 12rem;

    &::before {
      content: "";
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;

      margin: auto;

      width: 2rem;
      height: 12rem;

      background: #666;

      transform: rotate(90deg);
    }

    &::after {
      content: "";
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;

      margin: auto;

      width: 2rem;
      height: 12rem;

      background: #666;
    }
  }

  >.name,
  >.price {
    max-width: 90%;
  }
}

.activityPage {
  min-height: 100vh;
  max-height: 100vh;
  overflow-y: scroll;
  background-image: linear-gradient(160deg, rgb(255, 127, 92), #ea62ffe4);

  &::-webkit-scrollbar {
    display: none;
  }

  >.top {
    position: sticky;
    top: 0;

    height: 50rem;
    padding: 0 10rem;

    display: flex;
    align-items: center;

    color: #333;
    font-weight: 600;

    >.backBtn {
      font-size: 18rem;
    }

    >.title {
      position: absolute;
      left: 0;
      right: 0;
      margin: 0 auto;

      font-size: 20rem;
      width: max-content;
    }
  }

  >.user {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10rem 16rem 0rem;

    >.info {
      display: flex;
      align-items: center;

      >.img {
        width: 60rem;
        height: 60rem;
        border: 1rem solid #ccc;
        border-radius: 50%;

        overflow: hidden;

        >img {
          width: 100%;
          height: 100%;

          object-fit: cover;
          object-position: 0 center;
        }
      }

      >.name {
        font-size: 20rem;
        margin: 0 10rem;
        color: #222;
      }
    }

    >.btn {
      display: flex;
      font-size: 14rem;

      background: #fff;
      padding: 5rem 10rem;
      border-radius: 5rem;

      box-shadow: 3rem 3rem 10rem 0rem #626262b3;

      &:active {
        transform: translateY(1rem);
        box-shadow: unset;
      }
    }
  }

  >.second {
    position: relative;

    margin: 15rem 0;
    padding: 10rem;
    display: flex;
    flex-wrap: wrap;

    background: #fff;

    &::after,
    &::before {
      content: "";
      position: absolute;

      width: 12rem;
      height: 12rem;

      top: -11rem;
      left: 35rem;
    }

    &::before {
      background: radial-gradient(circle at 0 0, transparent 12rem, #fff 10rem);
    }

    &::after {
      left: 47rem;
      background: radial-gradient(circle at 100% 0,
          transparent 12rem,
          #fff 10rem);
    }

    >.item {
      @include item;
    }
  }

  :deep(.third) {
    margin-top: -60rem;
    padding: 10rem;
    background: #fff;

    border-radius: 5rem;

    width: 95%;

    display: flex;
    flex-wrap: wrap;

    >.item {
      @include item;
    }
  }

  >.invite {
    margin: 20rem 0;
    padding: 0 12rem;

    display: flex;
    flex-direction: column;

    font-size: 12rem;

    >.input {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 5rem 0;

      >input {
        padding: 0 4rem;
        width: 100rem;
        height: 22rem;
        line-height: 22rem;
      }

      >.btn {
        background: #fff;
        padding: 5rem 10rem;
        border-radius: 5rem;

        box-shadow: 3rem 3rem 10rem 0rem #4d4d4d77;

        &:active {
          transform: translateY(1rem);
          box-shadow: unset;
        }
      }
    }

    >span {
      color: #fff;
    }
  }

  >.tips {
    padding: 0 12rem;

    font-size: 14rem;
    line-height: 18rem;

    >span {
      font-size: 18rem;
    }
  }
}
</style>
